﻿<script lang="ts">
import type { PropType } from 'vue'
import { getIconList } from '@/plugins/svgIcon'
import { propTypes } from '@/utils/propTypes'

type iconType = {
	type:string;
	key:string;
	value:string;
}
export default defineComponent({
  name: 'SvgIcon',
  props: {
    // icon name
    icon: {
      type: String,
      required: true
    },
    // icon color
    color: propTypes.string,
    // icon size
    size: {
      type: [String, Number] as PropType<string | number>,
      default: 16
    },
    // icon class
    className: {
      type: String,
      default: () => ''
    }
  },
  setup(props) {
    const getIconStyle = computed(() => {
      return {
        fontSize: `${props.size}`.replace(/px/, '') + 'px',
        color: props.color
      }
    })
    const iconInfo = computed(():boolean|iconType => {
      return getSvgIcon(props.icon)
    })
    const svgClass = computed((): string => {
      if (props.className) {
        return 'svg-icon ' + props.className
      } else {
        return 'svg-icon'
      }
    })
    const getSvgIcon = (iconName:string):boolean|iconType => {
      const iconList:Array<iconType> = getIconList()
      if (iconName.indexOf(':') !== -1) {
        const iconType = iconName.split(':')[0]
        const iconKey = iconName.split(':')[1]
        const iconData = iconList.filter((item:iconType) => {
          return item.type === iconType && item.key === iconKey
        })[0]
        if (iconData) {
          return iconData
        } else {
          return false
        }
      } else {
        return false
      }
    }
    const valueIsBoolean = (val:any):val is boolean => {
      return typeof val === 'boolean'
    }
    return {
      getIconStyle,
      iconInfo,
      svgClass,
      valueIsBoolean
    }
  }
})
</script>

<template>
  <el-icon v-if="iconInfo" :style="getIconStyle">
    <svg v-if="!valueIsBoolean(iconInfo)&&iconInfo.type==='bi'" :class="svgClass" aria-hidden="true" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" v-html="iconInfo.value"></svg>
    <svg v-else-if="!valueIsBoolean(iconInfo)&&iconInfo.type==='ri'" :class="svgClass" aria-hidden="true" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" v-html="iconInfo.value"></svg>
    <svg v-else-if="!valueIsBoolean(iconInfo)&&iconInfo.type==='ii'" :class="svgClass" aria-hidden="true" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
      <use :xlink:href="'#'+iconInfo.value" />
    </svg>
    <svg v-else-if="!valueIsBoolean(iconInfo)&&iconInfo.type==='ad'||!valueIsBoolean(iconInfo)&&iconInfo.type==='ep'" :class="svgClass" aria-hidden="true" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" v-html="iconInfo.value"></svg>
    <component v-else :is="!valueIsBoolean(iconInfo)&&iconInfo.value" :class="svgClass"></component>
  </el-icon>
</template>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  overflow: hidden;
  vertical-align: -0.15em;
  fill: currentcolor;
}
</style>
